/*
 * You have two numbers represented by a linked list, where each node contains
 * a single digit. The digits are stored in reverse order, such that the 1's digit is at the head
 * of the list. Write a function that adds the two numbers and returns the sum as a linked list.
 * EXAMPLE
 * Input: (3 -> 1 -> 5) + (5 -> 9 -> 2)
 * Output: 8 -> 0 -> 8
 */
package Chapter2;

public class Chapter2_4 {
	public MyLinkedList addTwoLists(MyLinkedList list1, MyLinkedList list2)
	{
		MyLinkedListNode node1 = list1.Head;
		MyLinkedListNode node2 = list2.Head;
		MyLinkedList newList = new MyLinkedList();
		
		if(node1 == null)
			return list2;
		if(node2 == null)
			return list1;
		
		while(node1 != null && node2 != null)
		{
			newList.add(node1.value + node2.value);
			node1 = node1.Next;
			node2 = node2.Next;
		}
		
		if(node2 != null)
		{
			while(node2 != null)
			{
				newList.add(node2.value);
				node2 = node2.Next;
			}
		}else if(node1 != null)
		{
			while(node1 != null)
			{
				newList.add(node1.value);
				node1 = node1.Next;
			}
		}
		return newList;
	}
	
//	public static void main(String args[])
//	{
//		MyLinkedList list1 = new MyLinkedList();
//		list1.add(1);
//		list1.add(2);
//		list1.add(3);
//		MyLinkedList list2 = new MyLinkedList();
//		list2.add(1);
//		list2.add(2);
//		list2.add(4);
//		list2.add(2);
//		Chapter2_4 test = new Chapter2_4();
//		MyLinkedList list = test.addTwoLists(list1, list2);
//		list.checkResult();
//	}
}
